<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>医生排班设置</title>

  <!-- Bootstrap 4 & Icons -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css">

  <!-- Vue / Axios -->
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

  <style>
    :root{
  --card-radius:16px;
  --soft-shadow:0 10px 24px rgba(0,0,0,.06);
  --muted:#6c757d;
  --brand:#3b82f6;
}

    body{ font-size:18px; }
.page-title{ font-size:32px; margin:22px 0 12px; }
.sub-title{ font-size:16px; }

    .container-max{max-width:1440px;}
    .page-title{
      font-weight:800;
      letter-spacing:.02em;
      text-align:center;
      margin:20px 0 10px;
    }
    /* 小屏横向滚动条更易拖动 */
.grid-scroll{ padding-bottom:10px; }
    .sub-title{color:var(--muted); text-align:center; margin-bottom:22px}
    .meta-bar{
      background:#fff;border-radius:var(--card-radius);box-shadow:var(--soft-shadow);
      padding:14px 18px;margin-bottom:16px;display:flex;align-items:center;justify-content:space-between
    }
    .meta-item{font-weight:600}
    .meta-item small{color:var(--muted);font-weight:400;margin-left:6px}
    .quick-actions .btn{margin-right:8px;margin-bottom:8px}
    .board{
      background:#fff;border-radius:var(--card-radius);box-shadow:var(--soft-shadow);
      padding:18px;
    }
    /* 7列响应式栅格（窄屏横向滚动） */
    .grid-scroll{
      overflow-x:auto;padding-bottom:8px;
    }
    .grid-7{
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-gap: 10px;
  min-width: auto;
}
.grid-scroll{ overflow-x: visible; }
    .day-card{
      border:1px solid #eef0f4;border-radius:14px;background:#fafbff;
      transition:.2s;position:relative
    }
    .day-card:hover{box-shadow:0 8px 18px rgba(59,130,246,.12);transform:translateY(-2px)}
    .day-head{
      padding:12px 14px;border-bottom:1px solid #eef0f4;display:flex;align-items:center;justify-content:space-between
    }
    .day-head .badge{font-weight:600}
    .day-body{padding:12px 14px}
    .day-body .section{
        height: 108px;
    }
    .section{
      border:1px dashed #e4e7ee;border-radius:10px;background:#fff;padding:10px 10px;margin-bottom:10px
    }
    .section:last-child{margin-bottom:0}
    .section .section-title{
      display:flex;align-items:center;justify-content:space-between;margin-bottom:8px
    }
    .custom-switch .custom-control-label::before{top:.15rem;left:-2.25rem;width:2.5rem;height:1.3rem;border-radius:1rem}
    .custom-switch .custom-control-label::after{top:.3rem;left:-2.15rem;width:1rem;height:1rem;border-radius:50%}
    .mode-pill .btn{padding:.25rem .6rem;border-radius:999px}
    .inputs-row .form-control{ max-width:64px; padding:.15rem .35rem; height:28px; font-size:12px; }
    .inputs-row .sep{color:#adb5bd;margin:0 .35rem}
    .sticky-footer{
      position:sticky;bottom:0;background:#fff;border-top:1px solid #eef0f4;
      padding:14px;border-bottom-left-radius:var(--card-radius);border-bottom-right-radius:var(--card-radius)
    }
    .btn-lg-pill{border-radius:999px;padding:.65rem 1.25rem}
    /* 开关放大 */
.custom-switch .custom-control-label::before{
  top:.10rem; left:-2.55rem; width:2.9rem; height:1.6rem;
}
.custom-switch .custom-control-label::after{
  top:.28rem; left:-2.42rem; width:1.25rem; height:1.25rem;
}

  </style>
</head>
<body>
<div id="app" class="container container-max py-3">

  <h2 class="page-title">医生排班设置</h2>
  <div class="sub-title">更好用的号源配置与每周排班</div>

  <!-- 顶部信息 + 快捷操作 -->
  <div class="meta-bar">
    <div>
      <span class="meta-item">医生：<?= $goods['goods_name'] ?></span>
      <span class="meta-item ml-4">科室：<?= $cat['name'] ?><small>(goods_id: <?= $goods_id ?>)</small></span>
    </div>
    <div class="quick-actions">
      <button class="btn btn-outline-secondary btn-sm" @click="preset('wkday-am')"><i class="far fa-sun mr-1"></i>工作日全上午</button>
      <button class="btn btn-outline-secondary btn-sm" @click="preset('all-fixed-10')"><i class="fas fa-thumbtack mr-1"></i>全部固定10个</button>
      <button class="btn btn-outline-secondary btn-sm" @click="copyFrom(1)"><i class="far fa-copy mr-1"></i>复制周一到全周</button>
      <button class="btn btn-outline-danger btn-sm" @click="clearAll"><i class="far fa-trash-alt mr-1"></i>清空</button>
    </div>
  </div>

  <div class="board">
    <div class="grid-scroll">
      <div class="grid-7">

        <!-- 周卡片 -->
        <div class="day-card" v-for="(day, idx) in weeklySchedule" :key="day.week_day">
          <div class="day-head">
            <div class="h6 mb-0 font-weight-bold">{{ daysOfWeek[idx] }}</div>
            <span class="badge badge-light">{{ enabledCount(day) }} 时段</span>
          </div>
          <div class="day-body">

            <!-- 时段：上午/下午/夜间 -->
            <div class="section" v-for="section in ['morning','afternoon','night']" :key="section">
              <div class="section-title">
                <div class="d-flex align-items-center">
                  <span class="mr-2 font-weight-bold">
                    <i :class="sectionIcon(section)" class="mr-1"></i>{{ sectionName[section] }}
                  </span>
                </div>
                <div class="custom-control custom-switch">
                  <input type="checkbox" class="custom-control-input"
                         :id="`sw-${day.week_day}-${section}`"
                         v-model="day[section].enabled">
                  <label class="custom-control-label" :for="`sw-${day.week_day}-${section}`"></label>
                </div>
              </div>

              <div v-if="day[section].enabled">
                <!-- 模式：固定 / 随机 -->
                <div class="btn-group btn-group-sm mode-pill mb-2">
                  <button type="button" class="btn"
                          :class="day[section].mode==='fixed' ? 'btn-primary' : 'btn-outline-primary'"
                          @click="day[section].mode='fixed'">
                    固定
                  </button>
                  <button type="button" class="btn"
                          :class="day[section].mode==='random' ? 'btn-primary' : 'btn-outline-primary'"
                          @click="day[section].mode='random'">
                    随机
                  </button>
                </div>

                <!-- 输入 -->
                <div class="inputs-row d-flex align-items-center">
                  <template v-if="day[section].mode==='fixed'">
                    <input type="number" class="form-control form-control-sm"
                           min="0" v-model.number="day[section].fixed_num">
                    <span class="text-muted ml-2">个</span>
                  </template>
                  <template v-else>
                    <input type="number" class="form-control form-control-sm"
                           min="0" v-model.number="day[section].random_min">
                    <span class="sep">~</span>
                    <input type="number" class="form-control form-control-sm"
                           :min="day[section].random_min||0" v-model.number="day[section].random_max">
                    <span class="text-muted ml-2">个</span>
                  </template>
                </div>
              </div>
              <div v-else class="text-muted small">未启用</div>
            </div>

          </div>
        </div>
        <!-- /周卡片 -->

      </div>
    </div>

    <div class="sticky-footer d-flex justify-content-between align-items-center">
      <div class="text-muted small">
        <i class="far fa-lightbulb mr-1"></i> 提示：随机模式会在最小~最大范围内每天生成不同的号源数。
      </div>
      <div>
        <button class="btn btn-lg-pill btn-outline-secondary mr-2" @click="goBack"><i class="fas fa-chevron-left mr-1"></i>返回</button>
        <button class="btn btn-lg-pill btn-primary" @click="submitSchedule"><i class="fas fa-save mr-1"></i>提交排班</button>
      </div>
    </div>
  </div>
</div>

<script>
new Vue({
  el:'#app',
  data(){
    return {
      goods_id: <?= $goods_id ?>,
      daysOfWeek:['周一','周二','周三','周四','周五','周六','周日'],
      sectionName:{morning:'上午',afternoon:'下午',night:'夜间'},
      weeklySchedule:[]
    }
  },
  mounted(){
    this.initSchedule();
     // 加载后端数据
    this.loadSchedule();
  },
  methods:{
    sectionIcon(s){
      if(s==='morning') return 'far fa-sun';
      if(s==='afternoon') return 'fas fa-cloud-sun';
      return 'far fa-moon';
    },
    enabledCount(day){
      return ['morning','afternoon','night'].filter(s=>day[s].enabled).length;
    },
    goBack(){ history.back(); },

    // 初始化结构
    initSchedule(){
      this.weeklySchedule = [];
      for(let i=1;i<=7;i++){
        this.weeklySchedule.push({
          week_day:i,
          morning:{enabled:false,mode:'fixed',fixed_num:10,random_min:5,random_max:10},
          afternoon:{enabled:false,mode:'fixed',fixed_num:10,random_min:5,random_max:10},
          night:{enabled:false,mode:'fixed',fixed_num:10,random_min:5,random_max:10},
        })
      }
    },

    // 从后端载入排班+号源规则（延用你原有返回：{schedule, source_rules}）
    loadSchedule(){
      axios.get(`/store/goods/getWeeklySchedule?goods_id=${this.goods_id}`)
        .then(({data})=>{
          const {schedule=[], source_rules=[]} = data || {};
          // 勾选启用
          schedule.forEach(it=>{
            const d = this.weeklySchedule.find(x=>x.week_day===it.week_day);
            if(!d) return;
            if(it.morning) d.morning.enabled = true;
            if(it.afternoon) d.afternoon.enabled = true;
            if(it.night) d.night.enabled = true;
          });
          // 绑定规则
          source_rules.forEach(rule=>{
            const d = this.weeklySchedule.find(x=>x.week_day===rule.week_day);
            if(!d || !d[rule.section]) return;
            d[rule.section].mode = rule.mode || 'fixed';
            d[rule.section].fixed_num = Number(rule.fixed_num||10);
            d[rule.section].random_min = Number(rule.random_min||5);
            d[rule.section].random_max = Number(rule.random_max||10);
          });
        })
        .catch(err=>console.error('获取排班失败',err));
    },

    // 快捷：复制周 N 到全周
    copyFrom(weekDay){
      const src = this.weeklySchedule.find(d=>d.week_day===weekDay);
      if(!src) return;
      this.weeklySchedule.forEach(d=>{
        if(d.week_day===weekDay) return;
        ['morning','afternoon','night'].forEach(s=>{
          d[s].enabled = src[s].enabled;
          d[s].mode = src[s].mode;
          d[s].fixed_num = src[s].fixed_num;
          d[s].random_min = src[s].random_min;
          d[s].random_max = src[s].random_max;
        });
      });
    },

    // 快捷预置
    preset(type){
      if(type==='wkday-am'){
        this.weeklySchedule.forEach((d,idx)=>{
          const isWorkday = idx<5; // 周一~周五
          d.morning.enabled = !!isWorkday;
          if(isWorkday){
            d.morning.mode='fixed'; d.morning.fixed_num=10;
          }else{
            d.morning.mode='fixed'; d.morning.fixed_num=0;
          }
        });
      }
      if(type==='all-fixed-10'){
        this.weeklySchedule.forEach(d=>{
          ['morning','afternoon','night'].forEach(s=>{
            d[s].enabled=true; d[s].mode='fixed'; d[s].fixed_num=10;
          })
        })
      }
    },

    // 清空
    clearAll(){
      this.weeklySchedule.forEach(d=>{
        ['morning','afternoon','night'].forEach(s=>{
          d[s].enabled=false;
        })
      })
    },

    // 校验
    validate(){
      for(const d of this.weeklySchedule){
        for(const s of ['morning','afternoon','night']){
          const it=d[s]; if(!it.enabled) continue;
          if(it.mode==='fixed'){
            if(it.fixed_num<0){ alert('固定数量不能为负数'); return false; }
          }else{
            if(it.random_min<0 || it.random_max<0){ alert('随机最小/最大不能为负'); return false; }
            if(it.random_max < it.random_min){ alert('随机最大需 ≥ 最小'); return false; }
          }
        }
      }
      return true;
    },

    // 提交
    // 提交
// 提交
submitSchedule(){
  if(!this.validate()) return;
  axios.post(`/store/goods/editWeeklySchedule?goods_id=${this.goods_id}`, {
    schedule: this.weeklySchedule
  }).then(()=>{
    // 居中轻提示
    const ok = document.createElement('div');
    ok.className = 'alert alert-success text-center';
    ok.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 9999;
      padding: 20px 40px;
      font-size: 18px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    `;
    ok.innerHTML = '<i class="far fa-check-circle mr-1"></i> 已保存排班';
    document.body.appendChild(ok);

    // 2 秒后移除并返回上一页
    setTimeout(()=>{
      ok.remove();
      window.history.back();
    }, 2000);
  }).catch(err=>{
    console.error('提交失败', err);
    alert('提交失败，请重试');
  });
}
  }
})
</script>

</body>
</html>